package com.example.controller;

import com.demo.utils.ResponseResult;
import com.demo.utils.ResultUtils;
import com.example.dto.UserDto;
import com.example.jwt.JwtToken;
import com.example.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController1 {

    private Logger logger = LoggerFactory.getLogger(LoginController1.class);

    private UserService userService;

    public LoginController1(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户名密码登录
     *
     * @return token
     */
    @RequestMapping(value = "/login")
    public ResponseResult login(UserDto loginInfo, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginInfo.getUsername(), loginInfo.getPassword());
        subject.login(token);

        UserDto user = (UserDto) subject.getPrincipal();
//        String newToken = JwtTok(user.getUsername());
        String newToken = "";
        response.setHeader("x-auth-token", newToken);
        return ResultUtils.success(newToken);
    }


    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping(value = "/logout")
    public ResponseEntity<Void> logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipals() != null) {
            UserDto user = (UserDto) subject.getPrincipals().getPrimaryPrincipal();
            userService.deleteLoginInfo(user.getUsername());
        }
        SecurityUtils.getSubject().logout();
        return ResponseEntity.ok().build();
    }
    @RequestMapping(value = "/unauthorized")
    public ResponseResult unauthorized() {
        HttpStatus httpStatus = HttpStatus.UNAUTHORIZED;
        return ResultUtils.failure(httpStatus.value(),httpStatus.getReasonPhrase());
    }

}
